package classificazione;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Iterator;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import utils.Library;
import utils.LyricsGatherer;

import de.umass.lastfm.Track;

public class DocumentSimilarityClassificatore implements Classificatore{

	@Override
	public void searchSimilar(String text) throws Exception {
		String urlToCall = "http://www.scurtu.it/apis/documentSimilarity";
		String content;
		int similarity;
		int maxSimilarity = 0;
		Track mostSimilar;
		
		Collection<Track> tracks = Library.getTracks();
		Iterator<Track> iterator = tracks.iterator();
		Track track = null;
		while(iterator.hasNext()){
			track = iterator.next();
			content = "doc1=" + URLEncoder.encode(text, "UTF-8") + "&doc2=" + URLEncoder.encode(LyricsGatherer.getSongLyrics(track.getArtist(), track.getName()), "UTF-8");
			URL url = new URL(urlToCall); 
		    HttpURLConnection connection = (HttpURLConnection) url.openConnection();                       
		    connection.setDoOutput(true); 
		    connection.setDoInput (true);
		    connection.setUseCaches (false);        
		    connection.setInstanceFollowRedirects(false); 
		    connection.setRequestMethod("POST"); 
		    connection.setRequestProperty("Content-Type", "text/plain"); 
		    connection.setRequestProperty("charset", "utf-8");
		    connection.connect();
		    
		    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
		    output.writeBytes(content);
		    output.flush();
		    output.close();
		    
		    StringBuilder strBuffer = new StringBuilder();
		    String str = null;
		    BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		    while (null != ((str = input.readLine()))) {
		    	strBuffer.append(str);
		    }
		    Object obj=JSONValue.parse(strBuffer.toString());
		    JSONObject jsonObj = (JSONObject)obj;
		    similarity = Integer.parseInt((String) jsonObj.get("result"));
		    if(similarity>maxSimilarity){
		    	mostSimilar = track;
		    	maxSimilarity = similarity;
		    }
		}
		
	    
	    
	    
	}

}
